package com.liauto.timelist.ui.list

import android.annotation.SuppressLint
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.liauto.timelist.ui.BaseFragment
import com.liauto.timelist.databinding.FragmentListBinding
import com.liauto.timelist.databinding.LayoutTimeListItemBinding
import com.liauto.timelist.util.Adapter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class ListFragment : BaseFragment<FragmentListBinding, ListViewModel>() {

    companion object {
        fun newInstance() = ListFragment()
    }

    private val coroutineScope = CoroutineScope(Dispatchers.Main)
    private lateinit var adapter: Adapter<TimeListBean.Data, LayoutTimeListItemBinding>
    override fun provideViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): FragmentListBinding {
        return FragmentListBinding.inflate(inflater, container, false)
    }

    override fun provideViewModel(): ListViewModel {
        return ViewModelProvider(this)[ListViewModel::class.java]
    }

    @SuppressLint("SetTextI18n")
    override fun initEvent() {
        coroutineScope.launch {
            adapter = Adapter({ binding, data ->
                binding.timeName.text = data.name
                binding.time.text = "${data.hour}:${data.min}"
                binding.root.setOnClickListener{
                    replaceTimeFragment(data.hour, data.min)
                }
            }, { inflater, parent ->
                LayoutTimeListItemBinding.inflate(inflater, parent, false)
            })
            binding.recyclerview.layoutManager = LinearLayoutManager(requireContext()).apply {
                orientation = LinearLayoutManager.VERTICAL
            }
            binding.recyclerview.adapter = adapter
            viewModel.getTimeList(requireContext()).apply {
                when(code){
                    0 -> Toast.makeText(requireContext(),"网络连接失败，请检查网络连接",Toast.LENGTH_LONG).show()
                    400 -> Toast.makeText(requireContext(),message,Toast.LENGTH_LONG).show()
                    else -> adapter.dispatchUpdate(data)
                }
            }
        }
    }

}